const app = getApp()
let myname = ''


const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'


Page({
  data: {
    avatarUrl: defaultAvatarUrl,
    theme: wx.getSystemInfoSync().theme,
    myopenid:'',
    avatarUrlbase64:''
  },
  onLoad() {
    wx.onThemeChange((result) => {
      this.setData({
        theme: result.theme
      })
    })
    // const userInfo = wx.getStorageSync('userInfo');
    // app.globalData.userInfo = userInfo
    var openid = wx.getStorageSync('openid')
    console.log(openid)
    console.log(app.globalData.userInfo)
    this.setData({
        myopenid: openid
    })
  },
//   onChooseAvatar(e) {
//     const { avatarUrl } = e.detail 
//     this.setData({
//       avatarUrl,
//     })
//     console.log(this.data.avatarUrl)    
//     //  将头像上传到服务器
//     wx.uploadFile({
//         cloudPath:'avatar/' + new Date().getTime() + "_" +  Math.floor(Math.random()*1000) + ".jpg",
//         // url: 'https://example.weixin.qq.com/upload',
//         filePath: avatarUrl,
//         name: 'file',
//         success (res){
//           const data = res.data
//           //do something
//         }
//       })
//   },
  myname_input(e) { 
    myname = e.detail.value 
    console.log(myname)
  },

  onChooseAvatar(e) {
    const { avatarUrl } = e.detail 
    this.setData({
      avatarUrl,
    })
    this.data.avatarUrlbase64 = 'data:image/jpeg;base64,' +     wx.getFileSystemManager().readFileSync(e.detail.avatarUrl,'base64')
    console.log(this.data.avatarUrlbase64)
  },
  submit() {
      if (this.data.avatarUrl == defaultAvatarUrl) {
          wx.showToast({
              title: '请填充头像',
              icon: 'none'
          })
      } else {
          if (myname == '') {
              wx.showToast({
                  title: '请填写用户名',
                  icon: 'none'
              })
          } else {
              console.log(myname)
              app.globalData.userInfo.nickName = myname
              app.globalData.userInfo.avatarUrl = this.data.avatarUrlbase64
              console.log(app.globalData.userInfo)
              wx.setStorageSync('nickName', myname);
              wx.setStorageSync('avatarUrl', this.data.avatarUrlbase64);
              wx.cloud.database().collection('login_users').where({
                      _openid: this.data.myopenid
                  }).update({
                      data: {
                          avatarUrl: wx.cloud.database().command.set(this.data.avatarUrlbase64),
                          nickName: wx.cloud.database().command.set(myname)
                      }
                  })
                  .then(res => {
                      wx.switchTab({
                          url: '../my',
                      })
                  })
          }
      }
  }

})
